﻿using System.Collections.Generic;
using PureMVC.Interfaces;
using PureMVC.Other;
using System;

namespace PureMVC.Core
{
    public partial class Model : IModel
    {
        public Model(string _key)
        {
            if (instanceMap.ContainsKey(_key) && multitionKey != null)
            {
                throw new Exception(MULTITON_MSG);
            }
            multitionKey = _key;
            instanceMap.Add(_key, new WeakLazy<IModel>(() => this));
            proxyMap = new Dictionary<string, IProxy>();
            InitializeModel();
        }

        protected virtual void InitializeModel()
        {
        }

        public virtual void RegisterProxy(IProxy _proxy)
        {
            _proxy.InitializeNotifier(multitionKey);
            proxyMap[_proxy.ProxyName] = _proxy;
            _proxy.OnRegister();
        }

        public virtual IProxy RetrieveProxy(string _proxyName)
        {
            if (proxyMap.ContainsKey(_proxyName))
            {
                return proxyMap[_proxyName];
            }
            return null;
        }

        public virtual IProxy RemoveProxy(string _proxyName)
        {
            if (!proxyMap.ContainsKey(_proxyName))
            {
                return null;
            }
            var proxy = proxyMap[_proxyName];
            proxyMap.Remove(_proxyName);
            proxy.OnRemove();
            return proxy;
        }

        public virtual bool HasProxy(string _proxyName)
        {
            return proxyMap.ContainsKey(_proxyName);
        }

        protected string multitionKey;

        protected readonly Dictionary<string, IProxy> proxyMap;
    }
}